package com.handydata.antifraud.ws.dap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handydata.antifraud.annotation.Comment;
import com.handydata.antifraud.common.constant.DataSourceCode;
import com.handydata.antifraud.common.exception.WsInvokeException;
import com.handydata.antifraud.service.DataCallLogsService;
import com.handydata.antifraud.to.dap.DataTanZhiInfoReqTO;
import com.handydata.antifraud.to.dap.DataTanZhiInfoResTO;
import com.handydata.antifraud.util.DateUtil;
import com.handydata.antifraud.util.encrypt.Sha256Utils;
import com.handydata.antifraud.ws.WsInvocationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * 探知贷中报告
 */
@Slf4j
@Service("dataTanZhiInfoWsServiceImpl")
@Comment("探知贷中报告")
public class DataTanZhiInfoWsServiceImpl extends DataPlatformWsService<DataTanZhiInfoReqTO, DataTanZhiInfoResTO>
	implements WsInvocationService<DataTanZhiInfoReqTO, DataTanZhiInfoResTO> {

	@Autowired
	private DataCallLogsService dataCallLogsService;

	@Override
	public DataTanZhiInfoResTO query(DataTanZhiInfoReqTO req) throws WsInvokeException {
		log.info("探知贷中报告请求参数 {}", req);
		DataTanZhiInfoResTO resTO = new DataTanZhiInfoResTO();
		if (StringUtils.isEmpty(req.getName())) {
			log.error("探知贷中报告参数校验 {}", "name为空");
			resTO.setResCode("1111");
			resTO.setResMsg("探知贷中报告接口name参数为空");
			return resTO;
		}
		if (StringUtils.isEmpty(req.getIdCard())) {
			log.error("探知贷中报告参数校验 {}", "idCard为空");
			resTO.setResCode("1111");
			resTO.setResMsg("探知贷中报告接口idCard参数为空");
			return resTO;
		}
		if (StringUtils.isEmpty(req.getPhoneNum())) {
			log.error("探知贷中报告参数校验 {}", "phone为空");
			resTO.setResCode("1111");
			resTO.setResMsg("探知贷中报告接口phone参数为空");
			return resTO;
		}
		this.dataType = DataSourceCode.DATA_TAN_ZHI_INFO.getCode();
		resTO = executeQuery(req);
		// 行内压测挡板处理
//		try {
//			Thread.sleep(250);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
		//模拟数据源返回成功结果     
		// success
//		String data = "{\"resCode\":\"0000\",\"resMsg\":\"查询成功\",\"resData\":{\"reportNo\":\"DZ20191024095714900711\",\"reportTime\":\"2019-10-24 09:57\",\"requestInfo\":{\"trueName\":\"陈龙\",\"mobileNo\":\"18721895090\",\"backTime\":\"\",\"idCard\":\"441321197903152915\"},\"basicInfo\":{\"trueName\":\"陈龙\",\"idCard\":\"441321197903152915\",\"idLocation\":\"广东省惠阳县\",\"mobileNo\":\"18721895090\",\"mobileLocation\":\"上海\",\"mobileOperator\":\"中国移动\"},\"version\":\"1.0.0\",\"sections\":[{\"slice_name\":\"m1\",\"repay_fail_count\":0,\"repay_fail_sum\":1,\"loan_offer_sum\":0,\"loan_offer_count\":0},{\"slice_name\":\"m3\",\"repay_fail_count\":0,\"repay_fail_sum\":2,\"overdue_sum\":3,\"loan_offer_sum\":0,\"overdue_repay_sum\":0,\"sum_all_repay_succ_cnt\":0,\"loan_offer_count\":0},{\"slice_name\":\"m6\",\"overdue_sum\":4,\"loan_offer_sum\":0,\"overdue_repay_sum\":0,\"sum_all_repay_succ_cnt\":0,\"loan_offer_count\":0}],\"lastTime\":{\"repay_fail_last_to_now_d\":-1,\"loan_offer_last_to_now_d\":-1},\"tanzhenCount\":{\"m3\":0,\"m6\":0}}}";
		// fail
//		String data = "{\"resCode\":\"0000\",\"resMsg\":\"查询成功\",\"resData\":{\"reportNo\":\"DZ20191024095714900711\",\"reportTime\":\"2019-10-24 09:57\",\"requestInfo\":{\"trueName\":\"陈龙\",\"mobileNo\":\"18721895090\",\"backTime\":\"\",\"idCard\":\"441321197903152915\"},\"basicInfo\":{\"trueName\":\"陈龙\",\"idCard\":\"441321197903152915\",\"idLocation\":\"广东省惠阳县\",\"mobileNo\":\"18721895090\",\"mobileLocation\":\"上海\",\"mobileOperator\":\"中国移动\"},\"version\":\"1.0.0\",\"sections\":[{\"slice_name\":\"m1\",\"repay_fail_count\":6,\"repay_fail_sum\":0,\"loan_offer_sum\":0,\"loan_offer_count\":0},{\"slice_name\":\"m3\",\"repay_fail_count\":0,\"repay_fail_sum\":7,\"overdue_sum\":5,\"loan_offer_sum\":0,\"overdue_repay_sum\":0,\"sum_all_repay_succ_cnt\":0,\"loan_offer_count\":0},{\"slice_name\":\"m6\",\"overdue_sum\":9,\"loan_offer_sum\":0,\"overdue_repay_sum\":0,\"sum_all_repay_succ_cnt\":0,\"loan_offer_count\":0}],\"lastTime\":{\"repay_fail_last_to_now_d\":-1,\"loan_offer_last_to_now_d\":-1},\"tanzhenCount\":{\"m3\":0,\"m6\":0}}}";
////		JSONObject jasonObject = JSONObject.parseObject(data);
////		if ("0000".equals(jasonObject.getString("resCode"))) {
////			int m3RemindCount = 0;
////			int m6RemindCount = 0;
////			JSONObject resData = jasonObject.getJSONObject("resData");
////			if(resData != null) {
////				JSONArray sections = resData.getJSONArray("sections");
////				for(int i =0 ;i < sections.size();i++) {
////					JSONObject section = (JSONObject)sections.get(i);
////					if(section != null){
////						String sliceName = section.getString("slice_name");
////						if("m1".equals(sliceName)) {
////							int m1RepayFailSum = section.getInteger("repay_fail_sum");
////							resTO.setM1RepayFailSum(m1RepayFailSum);
////						}
////						if("m3".equals(sliceName)) {
////							m3RemindCount = section.getInteger("overdue_sum");
////							int m3RepayFailSum = section.getInteger("repay_fail_sum");
////							resTO.setM3RepayFailSum(m3RepayFailSum);
////						}
////						if("m6".equals(sliceName)) {
////							m6RemindCount = section.getInteger("overdue_sum");
////						}
////					}
////				}
////				resTO.setM3RemindCount(m3RemindCount);
////				resTO.setM6RemindCount(m6RemindCount);
////			}
////		}
////		resTO.setResCode((String)jasonObject.get("resCode"));
////		resTO.setResMsg((String)jasonObject.get("resMsg"));
		return resTO;
	}

	@Override
	protected String createQueryXml(DataTanZhiInfoReqTO req) {
		StringBuilder xml = new StringBuilder();
		xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
		xml.append("<subatm>");
		xml.append("<application>GwBiz.Req</application>");
		xml.append("<version>1.0.0</version>");
		xml.append("<sendTime>").append(DateUtil.now14()).append("</sendTime>");
		xml.append("<transCode>300663</transCode>");
		xml.append("<channelId>").append(encryInfo.getChannelId()).append("</channelId>");
		xml.append("<channelOrderId>").append(DateUtil.now17()).append("</channelOrderId>");
		xml.append("<name>").append(Sha256Utils.getSHA256Str(req.getName())).append("</name>");
		xml.append("<cid>").append(Sha256Utils.getSHA256Str(req.getIdCard())).append("</cid>");
		xml.append("<phone>").append(Sha256Utils.getSHA256Str(req.getPhoneNum())).append("</phone>");
//		xml.append("<name>").append(req.getName()).append("</name>");
//		xml.append("<cid>").append(req.getIdCard()).append("</cid>");
//		xml.append("<phone>").append(req.getPhoneNum()).append("</phone>");
		xml.append("<backTime>").append("</backTime>");
		xml.append("</subatm>");
		log.info("探知贷中报告调用翰迪数据平台请求报文{}", xml);
		req.setQueryXml(xml.toString());
		return xml.toString();
	}

	@Override
	protected DataTanZhiInfoResTO parseResultAndSave(String resultXml,	String orderId, Date createDate) {
		log.info("调用探知贷中报告接口返回报文：{}", resultXml);
		DataTanZhiInfoResTO resTO = new DataTanZhiInfoResTO();
		try {
			// 解析xml，保存本地DB
			JSONObject jasonObject = JSONObject.parseObject(resultXml);
			if ("0000".equals(jasonObject.getString("resCode"))) {
    			int m3RemindCount = 0;
    			int m6RemindCount = 0;
    			JSONObject resData = jasonObject.getJSONObject("resData");
    			if(resData != null && resData.get("sections") != null) {
    				JSONArray sections = resData.getJSONArray("sections");
    				for(int i =0 ;i < sections.size();i++) {
    					JSONObject section = (JSONObject)sections.get(i);
    					if(section != null){
    						String sliceName = section.getString("slice_name");
    						if("m1".equals(sliceName)) {
    							int m1RepayFailSum = section.getInteger("repay_fail_sum");
    							resTO.setM1RepayFailSum(m1RepayFailSum);
    						}
    						if("m3".equals(sliceName)) {
    							m3RemindCount = section.getInteger("overdue_sum");
    							int m3RepayFailSum = section.getInteger("repay_fail_sum");
    							resTO.setM3RepayFailSum(m3RepayFailSum);
    						}
    						if("m6".equals(sliceName)) {
    							m6RemindCount = section.getInteger("overdue_sum");
    						}
    					}
    				}
    				resTO.setM3RemindCount(m3RemindCount);
    				resTO.setM6RemindCount(m6RemindCount);
    			}
			}
			resTO.setResCode((String)jasonObject.get("resCode"));
			resTO.setResMsg((String)jasonObject.get("resMsg"));
		} catch (Exception e) {
			log.info("调用探知贷中报告接口异常：{}", e.getMessage());
			resTO.setResCode("1111");
			resTO.setResMsg("调用探知贷中报告接口异常");
		}
		log.info("调用探知贷中报告接口返回结果：{}", JSONObject.toJSONString(resTO));
		return resTO;
	}

	@SuppressWarnings("unchecked")
	@PostConstruct
	@Override
	public void register() {
		registerToWsServiceFactory(this, DataTanZhiInfoReqTO.class);
	}
    
}

